<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends MY_Controller {

	public function __construct() {
		parent::__construct();
		error_reporting(E_ALL);
		$this->load->library('form_validation');
		//设置表单错误分隔符，设置为空，直接输出即可
		$this->form_validation->set_error_delimiters('','');
		$this->load->model('member_model', 'member');
		error_reporting(E_ALL);
		$this->load->helper('public');
		
	}

	public function index() {
		redirect("/user/login");
	}

	public function login() {
		$config = array(
			array(
				'field' => 'account',
				'label' => '邮箱',
				'rules' => 'trim|required|callback_check_account'
				),
			array(
				'field' => 'password',
				'label' => '密码',
				'rules' => 'trim|required'
				)
		);
		$this->form_validation->set_rules($config);
		$this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
		$this->form_validation->set_message('check_email', '<i class="icon-exclamation-sign"></i>用户名格式不正确');

		if ($this->form_validation->run() == FALSE) {
			$this->load->view('/user/login');
		} else {
			$account = $this->input->post('account');
			$password = $this->input->post('password');

			if (empty($account)) {
				$data['error'] = '用户名或者密码错误';
				$this->load->view('/user/login', $data);
				return;
			}

			if (empty($password)) {
				$data['error'] = '用户名或者密码错误';
				$this->load->view('/user/login', $data);
				return;
			}
			$idnumberPattern = "/^[0-9]{8,9}$/u";

			if (preg_match($idnumberPattern, $account)) {
				$member = $this->member->select_one_by_field('idnumber', $account);
			} else {
				$member = $this->member->select_one_by_field('email', $account);
			}
			

			if (empty($member)) {
				$data['error'] = '用户名或者密码错误';
				$this->load->view('/user/login', $data);
				return;
			}
			//预留一个status，可以使得管理员禁止某些member登录
			if ($member['status'] === 0) {
				$data['error'] = '您的用户已经被锁定';
				$this->load->view('/user/login', $data);
				return;
			}
			//查看来访ip是否在被禁止ip的有效时间之内
			$ip = get_client_ip();

			if ($this->member->check_ip_banned($member["id"], $ip)) {
				$data['error'] = '密码错误次数太多，IP已经被禁止';
				$this->load->view('/user/login', $data);
				return;
			}


			if (!$this->checkHduPassword($member["idnumber"], $password)){
				$this->member->insert_log($member["id"], $ip, 0);
				$times = $this->member->get_last_login_fails($member["id"], $ip);
				if ($times['failedTimes'] >= $this->config->item("maxFailedTimes")) {
					$this->member->insert_ipbanned($member["id"], $ip);
					$data['error'] = '您的账户因为尝试次数过多，已经被锁定';
				} else {
					$times = intval($this->config->item("maxFailedTimes")) - intval($times['failedTimes']);
					$data['error'] = '密码错误，还剩余'.$times.'次';
				}
				
				$this->load->view('/user/login', $data);
				return;
			}

			$this->passLogin($member, 1);

			$this->roleLogin($member['id']);			
		}
	}
 
	/**
	 * [register 注册]
	 * @return [type] [description]
	 */
	public function register() {
		$config = array(
			array(
				'field' => 'email',
				'label' => '邮箱',
				'rules' => 'trim|required|callback_check_email'
				),
			array(
				'field' => 'password',
				'label' => '密码',
				'rules' => 'trim|required'
				),
			array(
				'field' => 'stuID',
				'label' => '学号',
				'rules' => 'tirm|required|callback_check_stuID'
				)
			);
		$this->form_validation->set_rules($config);
		$this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
		$this->form_validation->set_message('check_email', '<i class="icon-exclamation-sign"></i>用户名格式不正确');
		$this->form_validation->set_message('check_stuID', '<i class="icon-exclamation-sign"></i>学号格式不正确');
		if ($this->form_validation->run() === FALSE) {
			$this->load->view('/user/register');
		} else {
			$email 		= strtolower($this->input->post('email'));
			$password 	= $this->input->post('password');
			$stuID 		= $this->input->post('stuID');

			$member = $this->member->select_one_by_field('email', $email);

			if (!empty($member)) {
				$data['error'] = '邮箱已经被注册';
				$this->load->view('/user/register', $data);
				return;
			} 

			$stu = $this->member->select_one_by_field('idnumber', $stuID);

			if (!empty($stu)){
				$data['error'] = "该学号已经存在";
				$this->load->view('/user/register', $data);
				return ;
			}

			if (!$this->checkHduPassword($stuID, $password)) {
				$data['error'] = "教务系统密码错误";
				$this->load->view('/user/register', $data);
				return ;
			}

			$result = array(
				"idnumber" => $stuID,
				"email"    => $email,
				"password" => authcode($password, "encode", $this->config->item("password_encode_key")),
				);

			$passid =  $this->member->insert_member($result);
			
			if (empty($passid)) {
				//TDO: 这里应该写入日志
				$data['error'] = "信息插入失败，请联系管理员";
				$this->load->view('/user/register', $data);
				return ;
			}
			$member["id"] = $passid;
			$member["idnumber"] = $stuID;

			$this->passLogin($member);

			$this->roleLogin($passid);

			unset($member);
			
			//还可以做验证邮箱等操作
		}
	}
	/**
	 * [passLogin 建立session，建立cookie等]
	 * @param  [type] $passid [description]
	 * @return [type] $isRember        [1: 建立cookie, 0: 不建立cookie]
	 */
	protected function passLogin($member, $isRember = 0) {

		$_SESSION['passid'] = $member["id"];
		$_SESSION['stuID'] = $member["idnumber"];

		$ip = get_client_ip();
		$this->member->insert_log($member["id"], $ip);

		if ($isRember) {
			//TDO:建立cookie
			$cookie = array(
				'name'   => 'rd_passport',
				'value'  => 'loginin',
				'expire' => $this->config->item("cookie_time"),
				'domain' => '.redhome.cc',
				'path'   => '/',
				'prefix' => 'rdPassport_',
				'secure' => TRUE
				);
			$this->input->set_cookie($cookie);
		}
	}

	/**
	 * 处理角色登陆或者创建等业务
	 */ 
	protected function roleLogin($passid) {
		if (empty($passid)) {
			show_error("passid is NULL.the controller is roleLogin");
		}

		$defaultRole = $this->member->get_default_role($passid);

		if (empty($defaultRole)) {
			//跳转到创建角色页面
			redirect(site_url('/home/createrole'));
			//echo base_url('home/createrole');
		} else {
			$synLoginCode = uc_user_synlogin($defaultRole["uc_id"]);
			$goto = $this->input->get('goto');
			if (!empty($goto)) {
				show_message('登录成功'.$synLoginCode, $goto);
				return;
			}
			show_message('登录成功'.$synLoginCode, $this->config->item('bbs_path'));
			//echo '需要跳转到角色登陆';
		}
	}

	/*
	之前考虑有同学可能不愿意绑定教务系统密码，现在看来，还是先默认吧。
	 */
	/*protected function checkPassword($stuID, $password, $passwordInDatabase) {
		if ($this->checkHduPassword($stuID, $password)) {
			return TRUE;
		}
		//TDO:密码的加密方式还需替换
		if ($passwordInDatabase == $password) {
			return TRUE;
		}

		return FALSE;
	}*/


	

	/**
	 * 学校教务系统检查密码接口
	 * 
	 * */
	public function checkHduPassword($stuID, $password){
		$ch = curl_init();
		$apiUrl = "http://m.redhome.cc/api.php/jxgl/get_realinfo/verify?stuno={$stuID}&jxgl_pwd={$password}";
		curl_setopt($ch, CURLOPT_URL, $apiUrl);
	    curl_setopt($ch, CURLOPT_HEADER, 1);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    $content = curl_exec($ch);
	    curl_close($ch);
	    $pattern = "/(\{.*\})/ui";
	    preg_match($pattern, $content, $match);
	    $result = json_decode($match[0]);
	    if ($result->{"status"} == 1 && $result->{"message"} == "Verify Pass.") {
	    	return true;
	    } else {
	    	return false;
	    }
	}
	
	public function testing() {
		$goto = $this->input->get('goto');
		echo $goto;
	}

	public function check_email($account) {
		$emailPattern = "/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$/u";
		$idnumberPattern = "/^[0-9]{8,9}$/u";
		if (preg_match($emailPattern, $account)) {
			return TRUE;
		} else {
			if (preg_match($idnumberPattern, $account)) {
				return TRUE;
			} else {
				return FALSE;
			}
		}
	}

	public function check_stuID($stuID) {
		$pattern = "/^[0-9]{8,9}$/u";

		if (preg_match($pattern, $stuID)) {
			return TRUE;
		} else {
			return FALSE;
		}
	}


	public function ajaxLogin() {
		header('Content-type: text/html;charset=utf-8');

		$account = $this->input->post('account');
		$password = $this->input->post('password');

		if (empty($account)) {
			echo $this->formed_json_data(-1, "account_empty");
			return;
		}

		if (empty($password)) { 
			echo $this->formed_json_data(-2, "password_empty");
			return;
		}

		$idnumberPattern = "/^[0-9]{8,9}$/u";
		$emailPattern = "/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$/u";

		$accountValidation = 0;
		if (preg_match($idnumberPattern, $account)) {
			$accountValidation = 1;
			$member = $this->member->select_one_by_field('idnumber', $account);
		}

		if (preg_match($emailPattern, $account)) {
			$accountValidation = 1;
			$member = $this->member->select_one_by_field('email', $account);
		}

		if ($accountValidation == 0) {
			echo $this->formed_json_data(-3, "account_invalidate");
			return;
		}

		if (empty($member)) {
			echo $this->formed_json_data(-4, "member_notexisted");
			return;
		}

		if ($member["status"] == 0) {
			echo $this->formed_json_data(-5, "member_locked");
			return;
		}

		$ip = get_client_ip();

		if ($this->member->check_ip_banned($member["id"], $ip)) {
			echo $this->formed_json_data(-6, "member_failedToMuch");
			return;
		}

		if (!$this->checkHduPassword($member["idnumber"], $password)){
			$this->member->insert_log($member["id"], $ip, 0);
			$times = $this->member->get_last_login_fails($member["id"], $ip);
			if ($times['failedTimes'] >= $this->config->item("maxFailedTimes")) {
				$this->member->insert_ipbanned($member["id"], $ip);
				echo $this->formed_json_data(-5, "member_locked");
			} else {
				$times = intval($this->config->item("maxFailedTimes")) - intval($times['failedTimes']);
				echo $this->formed_json_data(-7, "password_uncorrect");
			}
			
			return;
		}

		$this->passLogin($member, 1);
		$memberData["passid"] = $member["id"];
		$memberData["idnumber"] = $member["idnumber"];
		$memberData["password"] = authcode($member["password"], "DECODE", $this->config->item("password_encode_key"));
		$memberData["emailstatus"] = $member["emailstatus"];
		$memberData["groupid"] = $member["groupid"];
		$memberData["adminid"] = $member["adminid"];
		$memberData["regdate"] = $member["regdate"];
		
		$profile = $this->member->get_profile($member["id"]);

		if (!empty($profile)) {
			$memberData["realname"] = $profile["realname"];
			$memberData["gender"] = $profile["gender"];
			$memberData["birth"] = $profile["birth"];
			$memberData["mobile"] = $profile["mobile"];
			$memberData["buildingNO"] = $profile["buildingNO"];
			$memberData["roomNO"] = $profile["roomNO"];
			$memberData["company"] = $profile["company"];
		}
		

		$defaultRole = $this->member->get_default_role($member["id"]);
		if (!empty($defaultRole)) {
			$memberData["roleName"] = $defaultRole["uc_name"];
			$memberData["rolePassword"] = authcode($defaultRole["uc_password"], "DECODE", $this->config->item("password_encode_key"));
			$memberData["ucid"] = $defaultRole["uc_id"];
		}
		
		$libaccount = $this->member->get_lib_password($member["id"]);
		$memberData["libpassword"] = authcode($libaccount["password"], "DECODE", $this->config->item("password_encode_key"));
		unset($libaccount);
		echo $this->formed_json_data(1, "success", $memberData);
		unset($member);
	}

	protected function formed_json_data($status, $message, $data = array()) {
		$jsonData= array(
			"status" => $status,
			"message" => $message,
			"data" => $data
			);
		return json_encode($jsonData);
	}

	public function hdu_test() {
		$ch = curl_init();
		$stuID = "11053428";
		$password = "Linux(2013)";
		$apiUrl = "http://m.redhome.cc/api.php/jxgl/get_realinfo/verify?stuno={$stuID}&jxgl_pwd={$password}";
		curl_setopt($ch, CURLOPT_URL, $apiUrl);
	    curl_setopt($ch, CURLOPT_HEADER, 1);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    $content = curl_exec($ch);
	    curl_close($ch);
	    $pattern = "/(\{.*\})/ui";
	    preg_match($pattern, $content, $match);
	    $result = json_decode($match[0]);
	    if ($result->{"status"} == 1 && $result->{"message"} == "Verify Pass.") {
	    	return true;
	    } else {
	    	return false;
	    }
	}
}